<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Log;

/**
 * APP端分类接口
 */
class Category extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    
    /**
     * 获取商品分类列表
     * @ApiMethod (GET)
     * @ApiParams (name="include_image", type="integer", required=false, description="是否包含图片，0不包含，1包含，默认1")
     */
    public function getList()
    {
        try {
            // 获取请求参数
            $includeImage = $this->request->param('include_image', 1, 'intval');
            
            // 构建查询字段
            $fields = ['id', 'parent_id', 'name', 'sort'];
            if ($includeImage) {
                $fields[] = 'image';
            }
            
            // 获取所有启用的分类
            $categories = Db::name('product_category')
                ->where('status', 1)
                ->field(implode(',', $fields))
                ->order('parent_id asc, sort asc, id asc')
                ->select();
            
            // 构建树形结构
            $tree = $this->buildCategoryTree($categories);
            
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => $tree
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取商品分类失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }
    
    /**
     * 获取子分类列表
     * @ApiMethod (GET)
     * @ApiParams (name="parent_id", type="integer", required=true, description="父级分类ID，0表示获取一级分类")
     * @ApiParams (name="include_image", type="integer", required=false, description="是否包含图片，0不包含，1包含，默认1")
     */
    public function getChildren()
    {
        try {
            // 获取请求参数
            $parentId = $this->request->param('parent_id', 0, 'intval');
            $includeImage = $this->request->param('include_image', 1, 'intval');
            
            // 构建查询字段
            $fields = ['id', 'parent_id', 'name', 'sort'];
            if ($includeImage) {
                $fields[] = 'image';
            }
            
            // 获取指定父级ID下的所有启用分类
            $categories = Db::name('product_category')
                ->where('status', 1)
                ->where('parent_id', $parentId)
                ->field(implode(',', $fields))
                ->order('sort asc, id asc')
                ->select();
            
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => $categories
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取子分类失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }
    
    /**
     * 构建分类树形结构
     */
    private function buildCategoryTree($categories, $parentId = 0)
    {
        $tree = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $children = $this->buildCategoryTree($categories, $category['id']);
                if (!empty($children)) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }
        return $tree;
    }
}